import React from "react";
import { LockOutlined, UserOutlined } from "@ant-design/icons";
import { message } from "antd";
import { ProFormText, LoginForm } from "@ant-design/pro-form";
import { history, useModel } from "umi";
import { login } from "@/services/admin";
import styles from "./index.less";

const Login = () => {
  const { initialState, setInitialState } = useModel("@@initialState");
  const fetchUserInfo = async () => {
    const adminInfo = await initialState?.fetchUserInfo?.();
    console.log("adminInfo", adminInfo);
    localStorage.setItem("adminInfo", JSON.stringify(adminInfo.user));
    if (adminInfo) {
      await setInitialState((s) => ({
        ...s,
        currentUser: { ...adminInfo.user },
      }));
    }
    const { routes } = initialState;
    // adminInfo 里面有permissions 和roles
    // const { permissionCodes } = adminInfo;
    // const first = permissionCodes[0];
    let path = "/pore";
    // routes.forEach((item) => {
    //   if (item.access === first) {
    //     path = item.path;
    //     if (item.routes) {
    //       path = item.routes[0].path;
    //     }
    //   }
    // });
    history.push(path);
  };

  const handleSubmit = async (values) => {
    try {
      // 登录
      const res = await login(values);
      console.log("res===", res);
      if (res.code === 200) {
        message.success("登录成功！");
        localStorage.setItem("access_token", res.data.access_token);
        await fetchUserInfo();
      }
    } catch (error) {}
  };

  return (
    <div className={styles.container}>
      {/* <div className={styles.lang} data-lang>
        {SelectLang && <SelectLang />}
      </div> */}
      <div className={styles.content}>
        <LoginForm
          // logo={<img alt="logo" src="/logo.svg" />}
          title="橡胶-3D打印"
          onFinish={async (values) => {
            await handleSubmit(values);
          }}
          initialValues={{
            username: "",
            password: "",
          }}
        >
          <>
            <ProFormText
              name="username"
              fieldProps={{
                size: "large",
                prefix: <UserOutlined className={styles.prefixIcon} />,
              }}
              placeholder="账号"
              rules={[
                {
                  required: true,
                  message: "请输入账号",
                },
              ]}
            />
            <ProFormText.Password
              name="password"
              fieldProps={{
                size: "large",
                prefix: <LockOutlined className={styles.prefixIcon} />,
              }}
              placeholder="密码"
              rules={[
                {
                  required: true,
                  message: "请输入密码",
                },
              ]}
            />
          </>
        </LoginForm>
      </div>
    </div>
  );
};

export default Login;
